import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

//Android、Flutter 相互通信
class MutualCommunicationWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState()  => MutualCommunicationState();
}

class MutualCommunicationState extends State<MutualCommunicationWidget> {

  final MethodChannel _channel = MethodChannel("mutual_communication_channel");



  //调用android 没有返回值
  Future<void> _test1() async {
    await _channel.invokeMethod("test1");
  }

  //调用android 有返回值
  Future<void> _test2() async {
    final result = await _channel.invokeMethod("test2");
    print("test2 结果：" + result);
  }

  //提供给Android调用
  void _initAndroidCall(){
    _channel.setMethodCallHandler((MethodCall call) async{
      print("Flutter代码 - setMethodCallHandler " + call.method +" , " + call.arguments);
      switch(call.method){
        case "test3" : {
          print("Flutter代码 - Android 调用 Flutter 没有返回值");
        }

        case "test4" :{
          print("Flutter代码 - Android 调用 Flutter 有返回值");
          return "this is flutter return 99";
        }
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _initAndroidCall();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Android、Flutter相互通信 - flutter页面"),
      ),

      body: Container(
        child: Column(
          children: [
            Text("相互通信1 - flutter"),
            ElevatedButton(onPressed: (){
              _test1();
            }, child: Text("调用原生方法 - 不返回值")),

            ElevatedButton(onPressed: (){
              _test2();
            }, child: Text("调用原生方法 - 有返回值"))
          ],
        ),
      ),
    );
  }
}